package com.mazaiting.web.auth.security.advice;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.mazaiting.auth.constant.AuthConstant;
import com.mazaiting.common.core.domain.result.Result;
import com.mazaiting.common.core.domain.result.ResultCode;
import com.mazaiting.web.auth.security.annotation.PrePermission;
import com.mazaiting.web.utils.UserUtil;
import com.mazaiting.redis.service.IRedisService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 权限校验切面
 */
@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class PrePermissionAdvice {

    private final IRedisService redisService;

    /**
     * 权限切点定义
     */
    @Pointcut("@annotation(com.mazaiting.web.auth.security.annotation.PrePermission)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("permission verification start.");
        // 方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 获取权限注解
        PrePermission prePermissionAnno = signature.getMethod().getAnnotation(PrePermission.class);
        // 不存在该注解则跳过
        if (Objects.nonNull(prePermissionAnno)) {
            // 需要的权限标识集合
            String[] requiredPerms = prePermissionAnno.value();
            log.info("required perms: " + Arrays.toString(requiredPerms));

            // 权限校验
            boolean passFlag = false;
            List<String> userRoles = UserUtil.getRoles();

            // 超级管理员放行
            if (UserUtil.isRoot()) {
                return joinPoint.proceed();
            }

            // 从 redis 中取角色权限数据
            Map<Object, Object> permRolesMap = redisService.hGetAll(AuthConstant.BTN_PERM_ROLES_KEY);
            if (CollectionUtil.isNotEmpty(permRolesMap)) {
                for (String requiredPerm : requiredPerms) {
                    // 拥有访问权限的角色
                    List<String> hasPermRoles = Convert.toList(String.class, permRolesMap.get(requiredPerm));
                    if (CollectionUtil.isNotEmpty(hasPermRoles)) {
                        for (String hasPermRole : hasPermRoles) {
                            boolean hasPerm = userRoles.stream().anyMatch(userRole -> userRole.equals(hasPermRole));
                            if (hasPerm) {
                                passFlag = true;
                                break;
                            }
                        }
                    }
                }
            }
            log.info("authentication result :{}", passFlag);
            if (!passFlag) {
                return Result.failed(ResultCode.ACCESS_UNAUTHORIZED);
            }
        }
        log.info("permission verification end.");
        return joinPoint.proceed();
    }

}
